<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>优惠券管理</el-breadcrumb-item>
      <el-breadcrumb-item>优惠券列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入优惠券内容（模糊搜索）"
            v-model="queryInfo.query"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="handleQueryOrder()"
            ></el-button> </el-input
        ></el-col>

        <el-col :span="8"
          ><el-button type="primary" @click="showAddDialog"
            >添加优惠券</el-button
          ></el-col
        >
      </el-row>

      <el-table
        :data="couponList"
        border
        style="width: 100%"
        :key="Math.random()"
      >
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="id" label="id"> </el-table-column>
        <el-table-column prop="name" label="优惠券名称" width="150px">
        </el-table-column>
        <!-- <el-table-column prop="goods_name" label="商品名称"> </el-table-column>
        <el-table-column
          prop="coupon_type.name"
          label="优惠券类型"
        ></el-table-column> -->
        <el-table-column prop="discount" label="折扣值"> </el-table-column>
        <el-table-column prop="limit_price" label="使用门槛金额">
        </el-table-column>
        <el-table-column prop="expire_time" label="过期时间（天）">
        </el-table-column>

        <el-table-column prop="total_count" label="总发放数量">
        </el-table-column>
        <el-table-column prop="surplus_count" label="剩余数量">
        </el-table-column>
        <el-table-column prop="is_new_comer" label="新人专享" width="80px">
          <template slot-scope="scope">
            <el-tag type="warning" v-if="scope.row.is_new_comer">是</el-tag>
            <el-tag type="warning" v-else style="opacity: 0">否</el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="create_time" label="创建时间" width="200px">
          <template slot-scope="scope">
            {{ scope.row.create_time | dateFormat }}
          </template>
        </el-table-column> -->

        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <!-- 详细信息 -->
            <el-tooltip
              :enterable="false"
              effect="dark"
              content="详细信息"
              placement="top"
            >
              <el-button
                type="primary"
                icon="el-icon-postcard"
                circle
                @click="showInfoDialog(scope.row)"
              ></el-button>
            </el-tooltip>

            <!-- 修改按钮 -->
            <el-tooltip
              :enterable="false"
              effect="dark"
              content="修改"
              placement="top"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                circle
                @click="showEditDialog(scope.row)"
              ></el-button>
            </el-tooltip>

            <!-- 删除按钮 -->
            <el-tooltip
              :enterable="false"
              effect="dark"
              content="删除"
              placement="top"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                @click="removeById(scope.row.id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 显示详细数据 -->
    <el-dialog
      title="优惠券信息详情"
      :visible.sync="infoDialogVisible"
      width="80%"
    >
      <!-- 内容主体区 -->
      <el-descriptions title="优惠券信息" border :column="3">
        <el-descriptions-item label="id">{{
          currCoupon.id
        }}</el-descriptions-item>
        <el-descriptions-item label="优惠券名称">{{
          currCoupon.name
        }}</el-descriptions-item>
        <el-descriptions-item
          label="绑定商品id"
          v-if="currCoupon.goods_of_coupon.goods_id != null"
          >{{ currCoupon.goods_of_coupon.goods_id }}</el-descriptions-item
        >
        <el-descriptions-item
          label="绑定商品名称"
          v-if="currCoupon.goods_of_coupon.goods_id != null"
          >{{ currCoupon.goods.name }}</el-descriptions-item
        >

        <el-descriptions-item
          label="绑定商品封面"
          v-if="currCoupon.goods_of_coupon.goods_id != null"
          >{{ currCoupon.goods.cover_url }}</el-descriptions-item
        >
        <el-descriptions-item label="折扣值">{{
          currCoupon.discount
        }}</el-descriptions-item>
        <el-descriptions-item label="使用门槛金额">{{
          currCoupon.limit_price
        }}</el-descriptions-item>
        <el-descriptions-item label="过期时间（天）">{{
          currCoupon.expire_time
        }}</el-descriptions-item>
        <el-descriptions-item label="总发放数量">{{
          currCoupon.total_count
        }}</el-descriptions-item>
        <el-descriptions-item label="剩余数量">{{
          currCoupon.surplus_count
        }}</el-descriptions-item>
        <el-descriptions-item label="新人专属">{{
          currCoupon.is_new_comer
        }}</el-descriptions-item>
        <el-descriptions-item label="是否可领取">{{
          currCoupon.is_give
        }}</el-descriptions-item>
        <el-descriptions-item label="优惠券描述">{{
          currCoupon.details
        }}</el-descriptions-item>
      </el-descriptions>
      <!-- 底部按钮区 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="infoDialogVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 修改/添加 -->
    <el-dialog
      @close="dialogClosed"
      :title="is_add ? '添加' : '修改' + '优惠券'"
      :visible.sync="dialogVisible"
      width="70%"
    >
      <!-- 内容主体区 -->
      <el-form
        :model="formData"
        :rules="formDataRules"
        ref="formDataRef"
        label-width="120px"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="id">
              <el-input v-model="formData.id" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="优惠券名称" prop="name">
              <el-input v-model="formData.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="绑定商品" prop="goods_id">
              <el-select
                :disabled="findAllGoodsType(formData.coupon_type_id) || !is_add"
                v-model="formData.goods_id"
                filterable
                remote
                reserve-keyword
                placeholder="请输入商品名称"
                :remote-method="remoteMethod"
              >
                <el-option
                  v-for="item in goodsNameList"
                  :key="item.id"
                  :label="item.name + '-库存-' + item.count"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="折扣值" prop="discount">
          <el-input
            v-model="formData.discount"
            type="number"
            placeholder="打折请输入小于1以下的小数，如8折是0.8"
          ></el-input>
        </el-form-item>

        <el-row>
          <el-col :span="8">
            <el-form-item label="总共发放量" prop="total_count">
              <el-input
                v-model="formData.total_count"
                type="number"
              ></el-input> </el-form-item
          ></el-col>

          <el-col :span="8">
            <el-form-item label="使用门槛金额" prop="limit_price">
              <el-input v-model="formData.limit_price" type="number"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="有效期（天）" prop="expire_time">
              <el-input
                v-model="formData.expire_time"
                type="number"
              ></el-input> </el-form-item
          ></el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="优惠券种类" prop="category">
              <el-select
                v-model="formData.category"
                placeholder="请选择"
                :disabled="!is_add"
              >
                <el-option
                  v-for="item in couponCategory"
                  :key="item.key"
                  :label="item.name"
                  :value="item.key"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="优惠券类型" prop="coupon_type_id">
              <el-select
                v-model="formData.coupon_type_id"
                placeholder="请选择"
                :disabled="!is_add"
              >
                <el-option
                  v-for="item in couponTypeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select> </el-form-item
          ></el-col>
        </el-row>

        <el-row>
          <el-col :span="8"
            ><el-form-item label="是否新人专属" prop="is_new_comer">
              <el-switch
                v-model="formData.is_new_comer"
                active-text="是"
                inactive-text="否"
              >
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否可领取" prop="is_give">
              <el-switch
                v-model="formData.is_give"
                active-text="是"
                inactive-text="否"
              >
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="优惠券描述" prop="details">
          <el-input v-model="formData.details"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 5
      },
      couponList: [],
      goodsNameList: [],
      couponTypeList: [],
      total: 0,
      infoDialogVisible: false,
      currCoupon: {
        goods_of_coupon: {
          goods_id: ''
        },
        goods: {}
      },
      is_add: true,
      dialogVisible: false,
      formData: {
        id: '',
        name: '',
        goods_id: '',
        discount: '',
        limit_price: '',
        expire_time: '',
        total_count: '',
        is_new_comer: false,
        is_give: false,
        category: '',
        coupon_type_id: '',
        details: ''
      },
      formDataRules: {
        name: [
          {
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          }
        ],
        discount: [
          {
            required: true,
            message: '请输入折扣值',
            trigger: 'blur'
          }
        ],
        limit_price: [
          {
            required: true,
            message: '请输入使用门槛金额',
            trigger: 'blur'
          }
        ],
        expire_time: [
          {
            required: true,
            message: '请输入有效期',
            trigger: 'blur'
          }
        ],
        total_count: [
          {
            required: true,
            message: '请输入总发放量',
            trigger: 'blur'
          }
        ],
        details: [
          {
            required: true,
            message: '请输入优惠券描述',
            trigger: 'blur'
          }
        ],
        category: [
          {
            required: true,
            message: '请选择优惠券种类',
            trigger: 'blur'
          }
        ],
        coupon_type_id: [
          {
            required: true,
            message: '请选择优惠券类型',
            trigger: 'blur'
          }
        ]
      },
      couponCategory: []
    }
  },
  created() {
    this.getData()
    this.getcouponTypeList()
  },
  mounted() {
    this.couponCategory = [
      {
        ...this.$cv.Coupon
      },
      {
        ...this.$cv.Discount
      },
      {
        ...this.$cv.Shipping
      }
    ]

    // console.log(this.couponCategory, '种类')
  },
  methods: {
    async getData() {
      const { data: res } = await this.$http.get('/getCouponList', {
        params: this.queryInfo
      })

      // console.log(res)
      if (res.status !== 200) {
        return this.$message.error('获取优惠券列表失败')
      }

      // this.couponList = []
      this.total = res.data.totalNum
      this.couponList = res.data.data

      // this.$set(this.couponList, 'index', res.data.data)
      console.log(res)
    },

    async getGoodsById(id) {
      const { data: res } = await this.$http.get('/getSingleMinGoods/' + id)

      // console.log(res)
      if (res.status !== 200) {
        return this.$message.error('获取商品信息失败')
      }

      return res.data
    },

    async getcouponTypeList() {
      const { data: res } = await this.$http.get('/getCouponTypeList')

      // console.log(res)
      if (res.status !== 200) {
        return this.$message.error('获取商品类型信息失败')
      }

      this.couponTypeList = res.data
      console.log(res.data)
    },

    async showInfoDialog(coupon) {
      // console.log(coupon)
      this.currCoupon = coupon

      if (coupon.goods_of_coupon.goods_id != null) {
        const goods = await this.getGoodsById(coupon.goods_of_coupon.goods_id)
        this.currCoupon.goods = goods
      }

      this.infoDialogVisible = true
    },

    async submitData() {
      this.$refs.formDataRef.validate(async (valid) => {
        if (!valid) return

        // 判断是否为全平台
        if (!this.findAllGoodsType(this.formData.coupon_type_id)) {
          if (
            this.formData.goods_id === '' ||
            this.formData.goods_id.length === 0
          ) {
            this.$message.info('请指定绑定的商品')
            return
          }

          this.formData.all_goods = false
        } else {
          this.formData.goods_id = 0
          this.formData.all_goods = true
        }

        // 将字符数字转为数字
        this.formData.goods_id = parseInt(this.formData.goods_id)
        this.formData.category = parseInt(this.formData.category)
        // 如果是包邮券，将discount改为空
        this.formData.discount =
          this.formData.category === this.$cv.Shipping
            ? ''
            : parseFloat(this.formData.discount)
        // console.log(this.formData.limit_price)
        this.formData.limit_price = parseFloat(this.formData.limit_price)
        console.log(this.formData.limit_price)
        this.formData.expire_time = parseInt(this.formData.expire_time)
        this.formData.total_count = parseInt(this.formData.total_count)
        this.formData.coupon_type_id = parseInt(this.formData.coupon_type_id)
        let res
        if (this.is_add) {
          // 添加
          this.formData.id = 0
          const response = await this.updateCoupon(
            this.formData,
            '/saveCoupon',
            '添加优惠券成功'
          )
          res = response.data
        } else {
          // 修改
          const response = await this.updateCoupon(
            this.formData,
            '/updateCoupon',
            '修改优惠券成功'
          )
          res = response.data
        }

        if (res.status !== 200) {
          return this.$message.error(res.message)
        }

        this.dialogVisible = false
        // // 重新获取用户列表数据以更新
        this.getData()
        this.$forceUpdate()

        this.$message.success('保存优惠券信息成功')
      })
    },

    showEditDialog(coupon) {
      // console.log(coupon)
      this.is_add = false
      this.formData = {
        id: coupon.id,
        name: coupon.name,
        goods_id: coupon.all_goods ? '' : coupon.goods_of_coupon.goods_id,
        discount:
          coupon.category === this.$cv.Shipping.key ? 0 : coupon.discount,
        limit_price: coupon.limit_price,
        expire_time: coupon.expire_time,
        total_count: coupon.total_count,
        is_new_comer: coupon.is_new_comer,
        is_give: coupon.is_give,
        all_goods: coupon.all_goods,
        category: coupon.category,
        coupon_type_id: coupon.coupon_type_id,
        details: coupon.details
      }

      this.dialogVisible = true
    },

    showAddDialog() {
      this.is_add = true
      this.dialogVisible = true
    },

    updateCoupon(formData, url) {
      return this.$http.post(url, {
        ...formData
      })
    },

    dialogClosed() {
      this.dialogVisible = false
      this.formData = {
        id: '',
        name: '',
        goods_id: '',
        discount: '',
        limit_price: '',
        expire_time: '',
        total_count: '',
        is_new_comer: false,
        is_give: false,
        all_goods: false,
        details: ''
      }
    },

    async remoteMethod(e) {
      const { data: res } = await this.$http.get('/getGoodsNameList', {
        params: {
          query: e
        }
      })
      this.goodsNameList = res.data.data
      console.log(res.data.data)
    },

    async removeById(id) {
      // console.log(id)
      // 弹框询问删除
      const confirmRes = await this.$confirm('是否删除该优惠券信息', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)

      // 如果用户确认删除，返回的是文本confirm
      // 如果用户取消删除，返回的是cancel
      if (confirmRes !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      // this.editUserDeleted(id, true)
      const { data: res } = await this.$http.post('/deleteCoupon/' + id)
      if (res.status !== 200) {
        return this.$message.error(res.message)
      }
      // 更新数据
      this.getData()
      this.$message.success(res.message)
    },

    findAllGoodsType(id) {
      for (let i = 0; i < this.couponTypeList.length; i++) {
        if (
          this.couponTypeList[i].id === parseInt(id) &&
          this.couponTypeList[i].name === '全平台'
        ) {
          return true
        }
      }

      return false
    },
    handleQueryOrder() {
      this.queryInfo.pageNum = 1
      this.getData()
    },
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getData()
    },

    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage
      this.getData()
    }
  }
}
</script>

<style lang="less" scoped></style>
